package com.ruoyi.weixin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.weixin.Exception.BussnissExecption;
import com.ruoyi.weixin.entity.*;
import com.ruoyi.weixin.mapper.*;
import com.ruoyi.weixin.service.MinioService;
import com.ruoyi.weixin.service.PictureService;
import com.ruoyi.weixin.untils.FileTypeUtils;
import com.ruoyi.weixin.untils.ImageCompressUtils;
import com.ruoyi.weixin.untils.OssUtil;
import com.ruoyi.weixin.vo.PicsId;
import com.ruoyi.weixin.vo.TabName;
import com.ruoyi.weixin.vo.picOrderTime;
import com.ruoyi.weixin.vo.userId;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * (Picture)表服务实现类
 *
 * @author makejava
 * @since 2023-12-26 09:52:28
 */
@Service("pictureService")
public class PictureServiceImpl extends ServiceImpl<PictureMapper, Picture> implements PictureService {

    @Autowired
    UserMapper userMapper;
    @Autowired
    TabMapper tabMapper;
    @Autowired
    PictureMapper pictureMapper;
    @Autowired
    PicturesMapper picturesMapper;
    @Autowired
    PicUserMapper picUserMapper;
    @Autowired
    private MinioService minioService;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public R<?> selectHot(Picture picture) {
        Page<Picture> page = new Page<>(picture.getPageNum(), picture.getPageSize());

        IPage<String> pictureIPage = pictureMapper.selectHot(page, picture);
        return R.ok(pictureIPage);
    }

    @Override
    @Transactional
    public R<?> findSiPics(userId userid) {
        LambdaQueryWrapper<Pictures> wrapper = new LambdaQueryWrapper<>();
        List<Integer> picturesIds = picUserMapper.selectList(new LambdaQueryWrapper<PicUser>().eq(PicUser::getUserId, userid.getUserId()))
                .stream()
                .map(item -> item.getPicturesId())
                .collect(Collectors.toList());
        List<Integer> list = picturesMapper.selectList(wrapper.eq(Pictures::getStatus, 0).eq(Pictures::getUserId, userid.getUserId())).stream().map(item -> item.getId()).collect(Collectors.toList());
        picturesIds.addAll(list);
        if (picturesIds.isEmpty()) {
            throw new BussnissExecption(4000, "还没有创建过相册，快去创建把");
        }
        wrapper.clear();
        Page<Pictures> picturesPage = picturesMapper.selectPage(new Page<Pictures>(userid.getPageNum(), userid.getPageSize()), wrapper.in(Pictures::getId, picturesIds).orderByAsc(Pictures::getOrederby).orderByDesc(Pictures::getCreateBy));
        List<Pictures> pictures = picturesPage.getRecords();
        List<Picture> p = null;
        for (Pictures pics : pictures) {
            p = super.list(new LambdaQueryWrapper<Picture>().eq(Picture::getPId, pics.getId()).orderByDesc(Picture::getId).eq(Picture::getLajiId, 1).last("limit 1"));
            if (!p.isEmpty()) {
                pics.setPicUrl(p.get(0).getPicUrl());
            }
        }
        picturesPage.setRecords(pictures);
        return R.ok(picturesPage);
    }


    @Override
    public R<?> findGongPics(userId userid) {
        Page<Pictures> page = new Page<>(userid.getPageNum(), userid.getPageSize());
        Page<Pictures> picturesPage = picturesMapper.selectPage(page, new LambdaQueryWrapper<Pictures>().eq(Pictures::getStatus, 0).orderByAsc(Pictures::getCreateBy));
        List<Pictures> picturesList = picturesPage.getRecords();
        List<Picture> p = null;
        for (Pictures pics : picturesList) {
            p = super.list(new LambdaQueryWrapper<Picture>().eq(Picture::getPId, pics.getId()).orderByDesc(Picture::getId).eq(Picture::getLajiId, 1).last("limit 1"));
            if (!p.isEmpty()) {
                pics.setPicUrl(p.get(0).getPicUrl());
            }
        }
        picturesPage.setRecords(picturesList);
        return R.ok(picturesPage);
    }

    @Override
    public R<?> findPicByPicsId(PicsId picsId) {
        Page<Picture> page = new Page<>(picsId.getPageNum(), picsId.getPageSize());
        Page<Picture> page1 = super.page(page, new LambdaQueryWrapper<Picture>().eq(Picture::getLajiId, 1).eq(Picture::getPId, picsId.getId()).orderByDesc(Picture::getCreateTime));
        return R.ok(page1);
    }

    @Override
    public R<?> findLajiPics(userId userid) {
        Page<Picture> page = new Page<>(userid.getPageNum(), userid.getPageSize());
        IPage<String> lajiPics = pictureMapper.findLajiPics(page, userid.getUserId());
        return R.ok(lajiPics);
    }

    @Override
    public R<?> findPicByPicsIdAndtime(PicsId picsId) {
        Page<Picture> page = new Page<>(picsId.getPageNum(), picsId.getPageSize());
        IPage<picOrderTime> picByPicsIdAndtime = pictureMapper.findPicByPicsIdAndtime(page, picsId.getId());
        List<picOrderTime> orderTimes = picByPicsIdAndtime.getRecords();
        System.err.println(picByPicsIdAndtime.getRecords());
        List<String> list = null;
        for (picOrderTime orderTime : orderTimes) {
            list = pictureMapper.getpicBytime(orderTime.getDate(), picsId.getId());
            orderTime.setUrls(list);
        }
        picByPicsIdAndtime.setRecords(orderTimes);
        return R.ok(picByPicsIdAndtime);
    }

    @Override
    public R<?> newPics(Pictures pictures) {
        return R.ok(picturesMapper.insert(pictures));
    }

    @Override
    public R<?> uploadPic(MultipartFile file, String pid, String userId) {
        Map<String, String> upload = upload(file, "1", userId);
        return R.ok(upload);
    }

    @Override
    public R<?> uploadFrent(MultipartFile file, String userId) {
        Map<String, String> upload = upload(file, "2", userId);
        String url = upload.get("url");
        return R.ok(upload);
    }

    @Override
    public R<?> uploadAvator(MultipartFile file, String userId) {
        Map<String, String> upload = upload(file, "3", userId);
        return R.ok(upload.get("url"));
    }

    @Override
    public int removeByid(String id, String userId) {
        Picture picture = new Picture();
        picture.setLajiId(0);
        pictureMapper.update(picture, new LambdaQueryWrapper<Picture>().eq(Picture::getId, id));
        return 0;
    }

    @Override
    public int reset(String id, String userId) {
        LambdaQueryWrapper<Pictures> wrapper = new LambdaQueryWrapper<>();
        Pictures hui = picturesMapper.selectOne(wrapper.eq(Pictures::getTypeName, "恢复相册").eq(Pictures::getUserId, userId));
        if (hui == null) {
            Pictures pictures = new Pictures(null, "恢复相册", "", new Date(), null, "", "", "1", "2", null, "", "", Integer.parseInt(userId));
            picturesMapper.insert(pictures);
            hui = picturesMapper.selectOne(wrapper.eq(Pictures::getTypeName, "恢复相册").eq(Pictures::getUserId, userId));
            picUserMapper.insert(new PicUser(null, Integer.parseInt(userId), hui.getId()));
        }
        Picture picture = new Picture();
        picture.setLajiId(1);
        picture.setPId(hui.getId());
        pictureMapper.update(picture, new LambdaQueryWrapper<Picture>().eq(Picture::getPicUrl, id));
        return 0;
    }

    @Override
    public int deletePics(String id) {
        Picture picture = new Picture();
        picture.setLajiId(0);
        picUserMapper.delete(new LambdaQueryWrapper<PicUser>().eq(PicUser::getPicturesId,id));
        picturesMapper.deleteById(id);
        pictureMapper.update(picture, new LambdaQueryWrapper<Picture>().eq(Picture::getPId, id));
        return 0;
    }

    @Override
    @Transactional
    public int movePic(String id, String name) {
        Pictures pictures = picturesMapper.selectOne(new LambdaQueryWrapper<Pictures>().eq(Pictures::getTypeName, name));
        Picture picture = new Picture();
        picture.setPId(pictures.getId());
        picture.setId(Integer.parseInt(id));
        System.err.println(picture);
        int i = pictureMapper.updateById(picture);
        return i;
    }

    @Override
    public int findLajiAndDelete() {
        LambdaQueryWrapper<Picture> wrapper = new LambdaQueryWrapper<Picture>().eq(Picture::getLajiId, 0);
        List<Picture> pictures = pictureMapper.selectList(wrapper);
        String result=null;
        for (Picture picture : pictures) {
                Pattern pattern = Pattern.compile("com/(.*)");
                Matcher matcher = pattern.matcher(picture.getPicUrl());
                if (matcher.find()) {
                    result = matcher.group(1);
                    System.out.println(result);
                } else {
                    System.out.println("No match found");
                }
//                minioService.removeObject("xingyue",result);
                OssUtil.delete(result);
        }
        pictureMapper.delete(wrapper);
        return 0;
    }

    public Map<String, String> uploads(MultipartFile file, String type, String userId) {
        Map<String, String> map = new HashMap<>();
        String url ="";
        String fileType = FileTypeUtils.getFileType(file);

        if (fileType!=null) {
            url = minioService.putObject(file, "xingyue", fileType,userId);
        }
        String nickName = userMapper.selectById(userId).getNickName();
        map.put("nickName", nickName);
        map.put("url", url);
        return map;
    }

    public Map<String, String> upload(MultipartFile file, String type, String userId) {
        String a = uploadGetSize(userId);
        Map<String, String> map = new HashMap<>();
        if (file.getSize() == 0) {
            throw new BussnissExecption(5000, "请选择上传的文件");
        }
        if (!file.getOriginalFilename().endsWith(".jpg")||file.getOriginalFilename().endsWith(".png")||file.getOriginalFilename().endsWith(".jpeg")) {
            throw new BussnissExecption(5000, "文件类型不对");
        }
        if (file.getSize() > 50 * 1024 * 1024) {
            throw new BussnissExecption(5000, "上传图片大小不能超过50M!");
        }

        String nickName = userMapper.selectById(userId).getNickName();
        MultipartFile multipartFile;
        String saveFolder = "";
        String url ="";

        if (type == "1") {
            saveFolder = "HongMeng/" + userId + "/pic";
        } else if (type == "2") {
            saveFolder = "HongMeng/" + userId + "/fren";
        } else {
            saveFolder = "HongMeng/" + userId + "/avtor";
        }

        try {
            String fileName = file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf(".")) + "_" + System.currentTimeMillis();

            List<String> list = new ArrayList<>();
            list.add("26");
            list.add("27");
            list.add("28");
            list.add("34");
            list.add("49");
            if (list.contains(userId)){
                 url = OssUtil.upload(saveFolder, fileName, file);
                System.err.println("完整上传");
            }else {
                MultipartFile image = ImageCompressUtils.compressImage(file);
                 url = OssUtil.upload(saveFolder, fileName, image);
            }
//            sendFileAndString(file,saveFolder,fileName);

            map.put("nickName", nickName);
            map.put("url", url);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public String uploadGetSize(String userId){
//        3友链，0会员，1超级会员，2普通用户，30，31，32
        //普通用户 300m，会员2g, 超级会员1--
        String path="HongMeng/"+userId;
        long getsize = OssUtil.getsize(path);
        System.err.println(getsize);
        User user = userMapper.selectById(userId);
        Integer link = user.getFrentLink();
        if (user==null){
            throw new BussnissExecption("没有该用户");
        }
        if (link.equals(2)||link.equals(32)){
            if (getsize>314572800l){
                throw new BussnissExecption("空间不足联系管理员");
            }
        }else if(link.equals(0)||link.equals(30)){
            if (getsize>2147483648l){
                throw new BussnissExecption("空间不足联系管理员");
            }
        }

        return "";
    }
    public void sendFileAndString(MultipartFile file, String message,String fileName) {
        try {
            // 获取文件的字节数组
            byte[] fileBytes = file.getBytes();

            // 将文件字节数组和字符串封装为自定义对象
            FileAndStringMessage fileAndStringMessage = new FileAndStringMessage(fileBytes, message,fileName);

            String queue="picture.upoad";
            // 发送自定义对象作为消息
            rabbitTemplate.convertAndSend(queue,fileAndStringMessage);
            System.out.println("File and string message sent successfully.");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public R<?> findpicbytab(TabName tabName) {
        LambdaQueryWrapper<Tab> wrapper = new LambdaQueryWrapper<>();
        List<Tab> tabs = tabMapper.selectList(wrapper.like(Tab::getName, tabName.getTabName()));
        ArrayList<Integer> list = new ArrayList<>();
        if (!tabs.isEmpty()) {
            for (Tab tab : tabs) {
                if (tab.getParentId() == null) {
                    wrapper.clear();
                    List<Tab> tabList = tabMapper.selectList(wrapper.eq(Tab::getParentId, tab.getId()));
                    list.addAll(tabList.stream().map(item -> item.getId()).collect(Collectors.toList()));
                }
                list.add(tab.getId());
            }
            Page<Picture> page = new Page<>(tabName.getPageNum(), tabName.getPageSize());
            List<Integer> collect = list.stream().distinct().collect(Collectors.toList());
            IPage<String> pagePic = pictureMapper.findpicbytab(page, collect, tabName.getUserId());

            if (pagePic.getRecords().isEmpty()) {
                pagePic = pictureMapper.findGongpicbytab(page, collect);
            }
            return R.ok(pagePic);
        }
        return null;
    }
}
